import { defineStore } from 'pinia';
import authData from '../mock/authData.js';
import {UserApi} from "@/api/user/index.js";
/**
 * 用户认证状态管理库
 * 负责处理用户登录、注册、注销及个人信息管理
 */
export const useAuthStore = defineStore('auth', {
    state: () => ({
        user:null,
        token: null,
        roles: [],
        realName: "系统管理员",
        deptId: 1,
        deptName: "总部",
        isAuthenticated: false,
        hasLoadedDynamicRoutes: false,
        permissions: [],
        menuList: [],
    }),
    actions: {
        async login(formData){
            const promise = await UserApi.login(formData);

            this.isAuthenticated=true;

            this.user=promise.data.userEntity;
            this.token=promise.data.accessToken;

            await this.getUserAuthInfo();

        },
        async smsLogin(formData){
            const promise = await UserApi.smsLogin(formData);

            this.isAuthenticated=true;

            this.user=promise.data.userEntity;
            this.token=promise.data.accessToken;

            await this.getUserAuthInfo();

        },
        logout(){
            this.user=null;
            this.isAuthenticated=false;
            this.token=null;
            this.permissions = [];
            this.menuList = [];
        },
        async getUserAuthInfo(){
            const userAuthInfo = await UserApi.getUserAuthInfo();
            console.log('userAuthInfo', userAuthInfo);

            this.permissions = userAuthInfo.data.permissions;
            this.menuList = userAuthInfo.data.menuTree;
            this.roles = userAuthInfo.data.roles;
            this.realName = userAuthInfo.data.deptId;
            this.deptId = userAuthInfo.data.deptId;
            this.deptName = userAuthInfo.data.deptName;
        }

    }
})